<template>
  <div>
    <input ref="word-upload-input" class="word-upload-input" type="file" accept=".pdf, .docx, .doc" multiple @change="handleClick">
    <div
      class="drop"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      拖曳文件到此,或者
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        {{ fileName ? fileName : '点击浏览' }}
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function // eslint-disable-line
  },
  data() {
    return {
      loading: false,
      fileName: ''
    }
  },
  methods: {
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      console.log(files)
      try {
        for (let i = 0; i < files.length; i++) {
          if (!this.isWord(files[i])) {
            // eslint-disable-next-line no-throw-literal
            throw '只支持上传 .pdf, .docx, .doc文件'
          } else {
            this.upload(files[i])
          }
        }
      } catch (err) {
        this.$message({
          type: 'error',
          message: err
        })
      }
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['word-upload-input'].click()
    },
    handleUpload1() {
      this.$refs['word-upload-input1'].click()
    },
    handleClick(e) {
      const files = e.target.files
      //   console.log(files)
      for (let i = 0; i < files.length; i++) {
        this.upload(files[i])
      }
    },
    upload(rawFile) {
      this?.beforeUpload?.(rawFile)
      this?.onSuccess?.(rawFile)
    },
    isWord(file) {
      return /\.(pdf|docx|doc)$/.test(file.name)
    }
  }
}
</script>

<style scoped>
.word-upload-input{
  display: none;
  z-index: -9999;
}
.drop{
  border: 2px dashed #bbb;
  width: 300px;
  max-width: 100%;
  height: 50px;
  line-height: 50px;
  font-size: 15px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>